<template>
  <div>
    
    <el-header style="display: flex; align-items: center; justify-content: flex-start; padding-left: 5px; margin-top:5px; margin-bottom:5px">
     <i class="el-icon-location-information" style="font-size:20px; margin-right:5px">
      当前位置：操作日志管理
      </i>
    </el-header>
    <div class="search" style="display: flex; align-items: center; justify-content: space-between; padding-left: 5px;">
      <div style="display: flex; align-items: center;">
        <el-select v-model="selectedField" placeholder="选择搜索字段" style="width: 150px; margin-right: 10px;">
          
          <el-option label="姓名" value="field1"></el-option>
          <el-option label="工号" value="field2"></el-option>
          <el-option label="操作IP地址" value="field3"></el-option>
          <el-option label="操作时间" value="field4"></el-option>
          <el-option label="操作表名" value="field5"></el-option>
          <el-option label="操作内容" value="field6"></el-option>
          
        </el-select>
        <input type="text" v-model="searchKeyword" placeholder="输入关键词搜索" style="width: 200px;">
        <button @click="search" style="margin-left: 10px;">
          <i class="el-icon-search"></i>
        </button>
      </div>
      <div style="display: flex; align-items: center;">
        
        <button @click="fetchData" style="margin-left: 50px;">加载数据库内容</button>
        <button @click="uploadData" style="margin-left: 50px;">上传数据</button>
      </div>
    </div>
    <div class="table-container">
    <table class="custom-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>工号</th>
          <th>操作IP地址</th>
          <th>操作时间</th>
          <th>操作表名</th>
          <th>操作内容</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in currentData" :key=index>
          <td>{{ index+1+(currentPage-1)*itemsPerPage }}</td>
          <td>{{ item.field1 }}</td>
          <td>{{ item.field2 }}</td>
          <td>{{ item.field3 }}</td>
          <td>{{ item.field4 }}</td>
          <td>{{ item.field5 }}</td>
          <td>{{ item.field6 }}</td>
          <td>
            <button @click="deleteItem(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    </div>

      <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="userItemsPerPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>
// import paginationMixin from '@/mixins/paginationMixin.js';

import axios from 'axios';
export default {
  // mixins: [paginationMixin],
  beforeRouteEnter(to, from, next) {
    // 在进入路由之前执行初始化函数
    // 由于在这里无法访问组件实例 this，你需要通过 next() 回调函数访问组件实例
    next(vm => {
      // 调用组件实例的初始化函数
      vm.fetchData(); // 假设你的初始化函数叫做 initialize()
    });
  },
  data() {
    return {
      selectedField: 'field1', 
      currentPage: 1, // 当前页码
      userItemsPerPage: 10, // 每页显示条数
      items:[],//从数据库中获得的数据
      data: [/* 初始数据 */],
      searchKeyword: '',
    };
  },

  computed: {
       displayedData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.currentData.slice(startIndex, endIndex);
    },
    filteredData() {
      if (!this.searchKeyword) {
        return this.data;
      }
      return this.data.filter(item => 
    (typeof item.field1 === 'string' && item.field1.includes(this.searchKeyword)) ||
    (typeof item.field2 === 'string' && item.field2.includes(this.searchKeyword)) ||
    (typeof item.field3 === 'string' && item.field3.includes(this.searchKeyword)) ||
    (typeof item.field4 === 'string' && item.field4.includes(this.searchKeyword)) ||
    (typeof item.field5 === 'string' && item.field5.includes(this.searchKeyword)) ||
    (typeof item.field6 === 'string' && item.field6.includes(this.searchKeyword)) ||
    (typeof item.field1 === 'number' && item.field1.toString().includes(this.searchKeyword)) ||
    (typeof item.field2 === 'number' && item.field2.toString().includes(this.searchKeyword)) ||
    (typeof item.field3 === 'number' && item.field3.toString().includes(this.searchKeyword)) ||
    (typeof item.field4 === 'number' && item.field4.toString().includes(this.searchKeyword)) ||
    (typeof item.field5 === 'number' && item.field5.toString().includes(this.searchKeyword)) ||
    (typeof item.field6 === 'number' && item.field6.toString().includes(this.searchKeyword)) 

      );
    },
    totalPages() {
      return Math.ceil(this.filteredData.length / this.itemsPerPage);
    }
  },
  methods: {
    handleSizeChange(val) {
      this.userItemsPerPage = val; // 更新每页显示条数
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    handleCurrentChange(val) {
      this.currentPage = val; // 更新当前页码
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    updateCurrentData() {
      const start = (this.currentPage - 1) * this.userItemsPerPage;
      const end = start + this.userItemsPerPage;
      this.currentData = this.filteredData.slice(start, end); // 更新显示的数据
    },
  async uploadData() {
    try {
      // 构造要发送的数据
      const dataToSend = this.data;
      // 发送 POST 请求到服务器
      const response = await axios.post('http://localhost:8000/api/log/refresh', dataToSend);
    console.log(response)
      // 检查响应状态
    } catch (error) {
      console.error('上传数据时发生错误:', error.message);
    }
  },


     async fetchData() {
      try {
       this.data = []
        // 发送请求获取数据
        const response = await axios.get('http://localhost:8000/api/log/query');
            // 判断是否成功获取了数据
    if (response) {
      // 将获取的数据存储在组件中
      this.items = response.data;
      console.log('Data fetched successfully:', this.items);
       // 遍历 items 中的每个对象，将数据更新到 data 中
       
      this.items.forEach(item => {
        const newDataObject = {};
        newDataObject['field1'] = item.name;//用户姓名
        newDataObject['field2'] = item.number;//用户编号
        newDataObject['field3'] = item.IPaddress;//操作IP
        newDataObject['field4'] = item.operation_time;//操作时间
        newDataObject['field5'] = item.table_name;//操作表名
        newDataObject['field6'] = item.operation_content;//操作内容

        this.data.push(newDataObject);
        },

      );
    } else {
      console.error('Failed to fetch data.');
      alert('Failed to fetch data.');
    }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },


    deleteItem(index) {
      console.log(index)
     if (confirm("确认删除？")) {
    // 用户确认删除后执行删除操作
    // 根据索引删除对应的条目
    this.data.splice(index+(this.currentPage-1)*this.itemsPerPage, 1);
    // 重新渲染页面
    // 重新渲染页面的逻辑可以是重新获取数据，或者直接更新视图数据
    }},
    search() {
      console.log(this.filteredData)
      // 执行搜索
      if (this.selectedField && this.searchKeyword) {
        this.filteredData = this.data.filter(item => item[this.selectedField].includes(this.searchKeyword));
      } else {
        this.filteredData = this.data;
      }
      this.currentPage = 1; // 搜索后重置页码
      this.updateCurrentData();
    },

  }
};
</script>

<style>
.table-container {
  text-align: center;
  margin: auto;
}

.custom-table {
  border-collapse: collapse;
  width: 80%;
  margin-bottom: 20px;
}

.custom-table th,
.custom-table td {
  border: 1px solid black;
  padding: 8px;
}

.pagination {
  margin-top: 20px;
}

.pagination button {
  margin-right: 5px;
}
</style>
